package GateKeeper;

import java.awt.*;
import java.sql.*;

import javax.swing.*;

import Database.*;
import General.*;
import Exception.*;

public class AuthenticationPanel extends JPanel
{
	private JLabel labelLogin, labelPassword;
	private JTextField fieldLogin;
	private JPasswordField fieldPassword;
	private JButton buttonConnection;
	private boolean authorize = false;
	
	public AuthenticationPanel(CallDB callDB, Connection connection)
	{
		//Layout
		this.setLayout(null);
				
		creationComponent();
		showComponent();
	}
	
	public void verifyAuthentication(Connection connection) throws CheckDataException, LoadDriverException
	{
		//Retrieve information (Password, Firstname, Lastname, Manager)
		MyTableModel modelIdAccount = new AccountMgmt(connection).checkLogin(fieldLogin.getText());
		
		if(modelIdAccount.getRowCount() != 0) //If the account exists
		{
			Session session = new Session(new AccountMgmt(connection).selectOneElement((int)modelIdAccount.getValueAt(0, 0))); //Creation of a session objection

			if(new String(fieldPassword.getPassword()).equals(session.getPassword())) //If the password matched
			{
				GeneralMethod.setSession(session); //Keep the session object
				authorize = true;
			}
			else
				JOptionPane.showMessageDialog(null, "The specified login or password doesn't exist !", "Access refused", JOptionPane.ERROR_MESSAGE);
		}
		else
			JOptionPane.showMessageDialog(null, "The specified login or password doesn't exist !", "Access refused", JOptionPane.ERROR_MESSAGE);
	}
	
	public void creationComponent()
	{
		labelLogin = new JLabel("Login :");
		labelLogin.setFont(new Font("Arial", Font.PLAIN, 18));
		labelLogin.setForeground(Color.WHITE);
		
		labelPassword = new JLabel("Password :");
		labelPassword.setFont(new Font("Arial", Font.PLAIN, 18));
		labelPassword.setForeground(Color.WHITE);

		fieldLogin = new JTextField("Restiaux");
		fieldLogin.setFont(new Font("Arial", fieldLogin.getFont().getStyle(), 16));

		fieldPassword = new JPasswordField("Tigrou007");
		fieldPassword.setFont(new Font("Arial", fieldPassword.getFont().getStyle(), 16));
			
		buttonConnection = new JButton("Connection");
	}
	
	public void showComponent()
	{
		labelLogin.setBounds(79, 75, 100, 25);
		fieldLogin.setBounds(175, 75, 104, 25);
		labelPassword.setBounds(79, 110, 100, 25);
		fieldPassword.setBounds(175, 110, 104, 25);
		buttonConnection.setBounds(79, 460, 200, 25);
		
		this.add(labelLogin);
		this.add(labelPassword);
		this.add(fieldLogin);
		this.add(fieldPassword);
		this.add(buttonConnection);
		
		GraphicsSetting.setBackground(this, "image/Background-GK.png", 0, 0, 366, 540);
	}

	//Gettors
	public JButton getButtonConnection(){return buttonConnection;}
	public JTextField getFieldLogin(){return fieldLogin;}
	public JPasswordField getFieldPassword(){return fieldPassword;}
	public boolean getAuthorize(){return authorize;}
}